import controller.base
import json
import random
import top.api
import datetime


class SmsHandler(controller.base.BaseHandler):
    def post(self):
        code = ''
        sms_type = self.get_body_para('type')
        phone = self.get_body_para('phoneNo')
        if phone is None or sms_type is None:
            self.rsp(7, msg="parameter error")
            return
        if sms_type < 1 or sms_type > 2:
            self.rsp(1, msg="type error")
            return
        for i in range(6):
            code += str(random.randint(0, 9))
        req=top.api.AlibabaAliqinFcSmsNumSendRequest()
        req.set_app_info(top.appinfo("23400734", 'a47cb92d7d5f61ef1ebbc09ce8f4cfb0'))

        req.extend="123456"
        req.sms_type="normal"
        req.sms_free_sign_name="响臻科技"
        req.sms_param="{\"code\":\""+str(code)+"\",\"product\":\"SkinDiary\"}"
        req.rec_num=phone
        if sms_type == 2:
            sql = 'SELECT * FROM users WHERE phone = %s'
            user = self.db.get(sql, phone)
            if user is None:
                self.rsp(6, msg="phone number not registered")
                return
            req.sms_template_code="SMS_11605017"
        else:
            req.sms_template_code="SMS_11605019"
        try:
            resp= req.getResponse()
            if resp['alibaba_aliqin_fc_sms_num_send_response']['result']['success']:
                sql = "REPLACE INTO smscodes (phone,type,code,createTime) VALUES (%s,%s,%s,%s)"
                self.db.insert(sql, phone, sms_type, code, datetime.datetime.now().strftime("%y-%m-%d %H:%M:%S"))
                self.rsp(0)
            else:
                self.rsp(resp['alibaba_aliqin_fc_sms_num_send_response']['result']['err_code'], msg=resp['alibaba_aliqin_fc_sms_num_send_response']['result']['msg'])
        except top.api.base.TopException as e:
            self.rsp(e.errorcode, msg=e.submsg)
